const mongoose = require('mongoose');
const {
  User,
  Student,
  Teacher,
  Class,
  Dormitory,
  Attendance,
  Grade,
  MarketDepartment,
  Role,
  AuditLog
} = require('./models/db');

// 中文姓氏
const surnames = ['张', '李', '王', '刘', '陈', '杨', '赵', '黄', '周', '吴', '徐', '孙', '马', '朱', '胡', '郭', '何', '高', '林', '罗', '郑', '梁', '谢', '宋', '唐', '许', '韩', '冯', '邓', '曹'];
// 中文名字
const givenNames = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '军', '洋', '勇', '艳', '杰', '娟', '涛', '明', '超', '秀兰', '霞', '平', '刚', '桂英', '建华', '文', '华', '强', '建国', '建军', '国华', '志强'];

// 学院列表
const academies = ['人工智能学院', '数智传媒学院', '云计算学院', '鸿蒙学院', '元宇宙学院', '计算机科学技术学院'];

// 市场部列表
const marketDepartments = ['中原市场部', '保沧市场部', '辽冀市场部', '华东市场部', '华南市场部', '西南市场部', '西北市场部'];

// 学段列表
const stages = ['专业一', '专业二', '专业三', '专业四', '专业五', '专高一', '专高二', '专高三', '专高四', '专高五', '专高六'];

// 宿舍楼列表
const buildings = ['皇悦一期', '皇悦三期', '学一舍', '学二舍', '学三舍', '学四舍', '学五舍', '11舍', '12舍', '13舍'];

// 考勤状态
const attendanceStatuses = ['正常', '迟到', '早退', '缺席', '请假'];

// 学生状态
const studentStatuses = ['在读', '休学', '停课', '毕业'];

// 教师状态
const teacherStatuses = ['在职', '休假', '停职'];

// 角色名称
const roleNames = ['系统管理员', '院长', '主任', '讲师', '导员', '教务人员'];

// 科目列表
const subjects = ['前端开发', '后端开发', '数据库原理', '数据结构', '算法设计', '软件工程', '网络编程', '移动开发', '云计算基础', '人工智能基础'];

// 生成随机中文姓名
function randomChineseName() {
  const surname = surnames[Math.floor(Math.random() * surnames.length)];
  const givenName1 = givenNames[Math.floor(Math.random() * givenNames.length)];
  const givenName2 = Math.random() > 0.3 ? givenNames[Math.floor(Math.random() * givenNames.length)] : '';
  return surname + givenName1 + givenName2;
}

// 生成随机日期（在指定范围内）
function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

// 生成随机手机号
function randomPhone() {
  const prefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '150', '151', '152', '153', '155', '156', '157', '158', '159', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189'];
  const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
  const suffix = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  return prefix + suffix;
}

// 生成学号（S20230001格式）
function generateStudentId(start = 2023, index = 1) {
  const year = start + Math.floor(index / 10000);
  const num = (index % 10000).toString().padStart(5, '0');
  return `S${year}${num}`;
}

// 生成学工号（T20230001格式）
function generateTeacherId(start = 2023, index = 1) {
  const year = start + Math.floor(index / 10000);
  const num = (index % 10000).toString().padStart(5, '0');
  return `T${year}${num}`;
}

// 生成班级名称（2401A到2510C）
function generateClassName(year, month, suffix) {
  const yearStr = year.toString().slice(-2);
  const monthStr = month.toString().padStart(2, '0');
  const suffixChar = String.fromCharCode(65 + suffix); // A, B, C
  return `${yearStr}${monthStr}${suffixChar}`;
}

// 初始化数据库
async function seedDatabase() {
  try {
    await mongoose.connect('mongodb://localhost:27017/students_management');
    console.log('数据库连接成功');

    // 清空现有数据
    console.log('清空现有数据...');
    await User.deleteMany({});
    await Student.deleteMany({});
    await Teacher.deleteMany({});
    await Class.deleteMany({});
    await Dormitory.deleteMany({});
    await Attendance.deleteMany({});
    await Grade.deleteMany({});
    await MarketDepartment.deleteMany({});
    await Role.deleteMany({});
    await AuditLog.deleteMany({});
    console.log('数据清空完成');

    // 1. 创建角色权限数据
    console.log('创建角色权限数据...');
    const roles = [];
    const rolePermissions = {
      '系统管理员': ['所有权限'],
      '院长': ['查看所有数据', '审核', '统计'],
      '主任': ['管理教师', '查看班级', '审核'],
      '讲师': ['查看学生', '录入成绩', '查看考勤'],
      '导员': ['管理学生', '查看考勤', '添加评语'],
      '教务人员': ['管理成绩', '导入导出', '查看统计']
    };

    roleNames.forEach((roleName, index) => {
      roles.push({
        roleId: `ROLE${(index + 1).toString().padStart(3, '0')}`,
        roleName: roleName,
        description: `${roleName}角色，拥有相应的系统权限`,
        permissions: rolePermissions[roleName] || [],
        userCount: 0,
        createdAt: new Date(),
        updatedAt: new Date()
      });
    });
    const roleDocs = await Role.insertMany(roles);
    console.log(`创建了 ${roleDocs.length} 个角色`);

    // 2. 创建用户数据
    console.log('创建用户数据...');
    const users = [];
    
    // 系统管理员
    users.push({
      username: 'admin',
      password: 'admin123',
      role: 'admin',
      email: 'admin@sms.edu.cn',
      phone: '13800000001',
      lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
      createdAt: new Date()
    });

    // 创建各角色用户
    let teacherUserIndex = 0;
    let advisorUserIndex = 0;
    
    // 院长、主任、讲师、导员、教务人员
    const roleUserCounts = {
      'admin': 1, // 已创建admin
      'muster': 10, // 院长和主任
      'teacher': 30, // 讲师
      'user': 15 // 教务人员
    };

    // 院长和主任（10个）
    for (let i = 0; i < 10; i++) {
      const name = randomChineseName();
      users.push({
        username: `dean${i + 1}`,
        password: '123456',
        role: i < 5 ? 'muster' : 'muster',
        email: `dean${i + 1}@sms.edu.cn`,
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        createdAt: new Date()
      });
    }

    // 讲师（30个）
    for (let i = 0; i < 30; i++) {
      const name = randomChineseName();
      users.push({
        username: `teacher${i + 1}`,
        password: '123456',
        role: 'teacher',
        email: `teacher${i + 1}@sms.edu.cn`,
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        createdAt: new Date()
      });
    }

    // 导员（15个）
    for (let i = 0; i < 15; i++) {
      users.push({
        username: `advisor${i + 1}`,
        password: '123456',
        role: 'teacher', // 导员也用teacher角色
        email: `advisor${i + 1}@sms.edu.cn`,
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        createdAt: new Date()
      });
    }

    // 教务人员（15个）
    for (let i = 0; i < 15; i++) {
      users.push({
        username: `staff${i + 1}`,
        password: '123456',
        role: 'user',
        email: `staff${i + 1}@sms.edu.cn`,
        phone: randomPhone(),
        lastLogin: randomDate(new Date(2024, 0, 1), new Date()),
        createdAt: new Date()
      });
    }

    const userDocs = await User.insertMany(users);
    console.log(`创建了 ${userDocs.length} 个用户`);

    // 3. 创建市场部数据
    console.log('创建市场部数据...');
    const marketDeptDocs = [];
    for (let i = 0; i < marketDepartments.length; i++) {
      const dept = await MarketDepartment.create({
        name: marketDepartments[i],
        manager: randomChineseName(),
        studentCount: 0,
        graduateStatus: [
          {
            year: '2023',
            totalGraduates: Math.floor(Math.random() * 100) + 50,
            employed: Math.floor(Math.random() * 80) + 40,
            unemployed: Math.floor(Math.random() * 20) + 5,
            furtherEducation: Math.floor(Math.random() * 20) + 5
          },
          {
            year: '2024',
            totalGraduates: Math.floor(Math.random() * 120) + 60,
            employed: Math.floor(Math.random() * 100) + 50,
            unemployed: Math.floor(Math.random() * 25) + 5,
            furtherEducation: Math.floor(Math.random() * 25) + 5
          }
        ],
        createdAt: new Date(),
        updatedAt: new Date()
      });
      marketDeptDocs.push(dept);
    }
    console.log(`创建了 ${marketDeptDocs.length} 个市场部`);

    // 4. 创建教师数据
    console.log('创建教师数据...');
    const teachers = [];
    let teacherUserStart = 1; // admin是0
    
    // 从用户中创建对应的教师记录（院长、主任、讲师、导员）
    for (let i = 0; i < 55; i++) { // 10个院长/主任 + 30个讲师 + 15个导员
      const user = userDocs[teacherUserStart + i];
      const isAdvisor = i >= 40; // 后15个是导员
      const academy = academies[Math.floor(Math.random() * academies.length)];
      
      // 确保状态主要是"在职"
      let status = '在职';
      if (Math.random() > 0.9) { // 10%概率是其他状态
        status = teacherStatuses[Math.floor(Math.random() * teacherStatuses.length)];
      }
      
      teachers.push({
        teacherId: generateTeacherId(2020, i + 1),
        name: randomChineseName(),
        gender: Math.random() > 0.5 ? '男' : '女',
        academy: academy,
        phone: user.phone,
        status: status,
        classes: [],
        user: user._id,
        createdAt: new Date(),
        updatedAt: new Date()
      });
    }
    const teacherDocs = await Teacher.insertMany(teachers);
    console.log(`创建了 ${teacherDocs.length} 个教师`);

    // 5. 创建班级数据（2401A到2510C，约30个班级）
    console.log('创建班级数据...');
    const classes = [];
    const classNames = [];
    
    // 生成2024年1月到10月的班级（2401A, 2401B, 2401C 到 2410A, 2410B, 2410C）
    for (let year = 24; year <= 25; year++) {
      for (let month = 1; month <= 10; month++) {
        for (let suffix = 0; suffix < 3; suffix++) { // A, B, C
          if (year === 25 && month > 10) break; // 2510是最后
          classNames.push(generateClassName(year, month, suffix));
        }
      }
    }

    // 只取前30个班级
    const selectedClassNames = classNames.slice(0, 30);
    
    for (let i = 0; i < selectedClassNames.length; i++) {
      const academy = academies[Math.floor(Math.random() * academies.length)];
      const stage = stages[Math.floor(Math.random() * stages.length)];
      
      classes.push({
        className: selectedClassNames[i],
        academy: academy,
        stage: stage,
        advisor: null, // 稍后分配
        lecturer: null, // 稍后分配
        studentCount: 0,
        students: [],
        createdAt: new Date(),
        updatedAt: new Date()
      });
    }
    const classDocs = await Class.insertMany(classes);
    console.log(`创建了 ${classDocs.length} 个班级`);

    // 更新教师的所带班级
    // 导员（后15个教师）分配到班级作为导员
    const advisorTeachers = teacherDocs.slice(40); // 后15个是导员
    const lecturerTeachers = teacherDocs.slice(10, 40); // 中间30个是讲师
    
    // 为每个班级分配导员和讲师
    for (let i = 0; i < classDocs.length; i++) {
      const classDoc = classDocs[i];
      
      // 为班级分配导员（从导员中循环分配）
      if (advisorTeachers.length > 0) {
        const advisorIndex = i % advisorTeachers.length;
        classDoc.advisor = advisorTeachers[advisorIndex]._id;
        
        // 同时将该班级添加到导员的classes列表
        if (!advisorTeachers[advisorIndex].classes.some(c => c.toString() === classDoc._id.toString())) {
          advisorTeachers[advisorIndex].classes.push(classDoc._id);
          await advisorTeachers[advisorIndex].save();
        }
      }
      
      // 为班级分配讲师（从讲师中随机分配，但尽量让每个讲师都有班级）
      if (lecturerTeachers.length > 0) {
        const lecturerIndex = Math.floor(Math.random() * lecturerTeachers.length);
        classDoc.lecturer = lecturerTeachers[lecturerIndex]._id;
        
        // 同时将该班级添加到讲师的classes列表
        if (!lecturerTeachers[lecturerIndex].classes.some(c => c.toString() === classDoc._id.toString())) {
          lecturerTeachers[lecturerIndex].classes.push(classDoc._id);
          await lecturerTeachers[lecturerIndex].save();
        }
      }
      
      await classDoc.save();
    }
    
    // 为其他教师（讲师）也随机分配一些班级
    for (let i = 0; i < lecturerTeachers.length; i++) {
      const teacher = lecturerTeachers[i];
      // 如果还没有分配班级，随机分配1-2个
      if (teacher.classes.length === 0) {
        const assignedClasses = [];
        const classCount = Math.floor(Math.random() * 2) + 1;
        for (let j = 0; j < classCount && assignedClasses.length < classDocs.length; j++) {
          const randomClass = classDocs[Math.floor(Math.random() * classDocs.length)];
          if (!assignedClasses.includes(randomClass._id.toString()) && 
              !teacher.classes.some(c => c.toString() === randomClass._id.toString())) {
            assignedClasses.push(randomClass._id.toString());
            teacher.classes.push(randomClass._id);
          }
        }
        await teacher.save();
      }
    }

    // 6. 创建宿舍数据
    console.log('创建宿舍数据...');
    const dormitories = [];
    for (let b = 0; b < buildings.length; b++) {
      const building = buildings[b];
      const floors = building.includes('皇悦') ? 10 : 6; // 皇悦楼层多
      
      for (let floor = 1; floor <= floors; floor++) {
        const roomsPerFloor = 20; // 每层20个房间
        for (let room = 1; room <= roomsPerFloor; room++) {
          dormitories.push({
            building: building,
            floor: floor,
            roomNumber: room.toString().padStart(3, '0'),
            capacity: 8,
            students: [],
            comment: '',
            createdAt: new Date(),
            updatedAt: new Date()
          });
        }
      }
    }
    const dormitoryDocs = await Dormitory.insertMany(dormitories);
    console.log(`创建了 ${dormitoryDocs.length} 个宿舍`);

    // 7. 创建学生数据（500个学生）
    console.log('创建学生数据...');
    const students = [];
    const admissionStartDate = new Date('2024-01-01');
    const admissionEndDate = new Date('2525-10-31');
    
    // 确保每个班级都有学生，学生平均分配
    const studentsPerClass = Math.floor(500 / classDocs.length);
    let studentIndex = 0;
    
    for (let i = 0; i < 500; i++) {
      const studentId = generateStudentId(2023, i + 1);
      const name = randomChineseName();
      const gender = Math.random() > 0.5 ? '男' : '女';
      
      // 确保学生分配到合适的班级（相同学院）
      let classDoc;
      if (i < classDocs.length * studentsPerClass) {
        // 前N个学生按班级分配
        const classIdx = Math.floor(i / studentsPerClass) % classDocs.length;
        classDoc = classDocs[classIdx];
      } else {
        // 剩余学生随机分配
        classDoc = classDocs[Math.floor(Math.random() * classDocs.length)];
      }
      
      const academy = classDoc.academy; // 使用班级的学院
      const marketDept = marketDepartments[Math.floor(Math.random() * marketDepartments.length)];
      const admissionDate = randomDate(admissionStartDate, admissionEndDate);
      const stage = classDoc.stage; // 使用班级的阶段
      
      // 临时记录，稍后统一分配宿舍
      // 先不分配宿舍，等学生创建完成后再按性别分配
      let dormitory = null; // 临时设为null
      
      const status = studentStatuses[Math.floor(Math.random() * studentStatuses.length)];
      
      students.push({
        studentId: studentId,
        name: name,
        gender: gender,
        academy: academy,
        marketDepartment: marketDept,
        admissionDate: admissionDate,
        class: classDoc._id,
        stage: stage,
        dormitory: null, // 稍后分配
        phone: randomPhone(),
        status: status,
        teacherComments: [],
        createdAt: new Date(),
        updatedAt: new Date()
      });
      
      studentIndex++;
    }
    const studentDocs = await Student.insertMany(students);
    console.log(`创建了 ${studentDocs.length} 个学生`);

    // 更新班级的学生列表和学生人数
    for (const classDoc of classDocs) {
      const classStudents = studentDocs.filter(s => s.class.toString() === classDoc._id.toString());
      classDoc.students = classStudents.map(s => s._id);
      classDoc.studentCount = classStudents.length;
      await classDoc.save();
    }

    // 为学生分配宿舍（按性别分组，每个宿舍最多8人）
    console.log('为学生分配宿舍...');
    
    // 先清空所有宿舍的学生列表
    for (const dorm of dormitoryDocs) {
      dorm.students = [];
      await dorm.save();
    }
    
    // 重新获取最新的宿舍数据
    const freshDorms = await Dormitory.find().exec();
    
    const maleStudents = studentDocs.filter(s => s.gender === '男');
    const femaleStudents = studentDocs.filter(s => s.gender === '女');
    
    // 分配男生宿舍 - 使用前一半宿舍
    let maleDormIndex = 0;
    for (let i = 0; i < maleStudents.length; i++) {
      let assigned = false;
      let attempts = 0;
      
      while (!assigned && attempts < freshDorms.length) {
        const dorm = freshDorms[maleDormIndex % freshDorms.length];
        maleDormIndex++;
        
        // 检查宿舍当前学生数量
        const currentStudentsInDorm = studentDocs.filter(s => s.dormitory && s.dormitory.toString() === dorm._id.toString());
        const currentCount = currentStudentsInDorm.length;
        
        // 检查是否有女生
        const hasFemale = currentStudentsInDorm.some(s => s.gender === '女');
        
        if (currentCount < dorm.capacity && !hasFemale) {
          // 分配到这个宿舍
          maleStudents[i].dormitory = dorm._id;
          await maleStudents[i].save();
          assigned = true;
        }
        
        attempts++;
      }
    }
    
    // 分配女生宿舍 - 使用后一半宿舍
    let femaleDormIndex = Math.floor(freshDorms.length / 2);
    for (let i = 0; i < femaleStudents.length; i++) {
      let assigned = false;
      let attempts = 0;
      
      while (!assigned && attempts < freshDorms.length) {
        const dorm = freshDorms[femaleDormIndex % freshDorms.length];
        femaleDormIndex++;
        
        // 检查宿舍当前学生数量
        const currentStudentsInDorm = studentDocs.filter(s => s.dormitory && s.dormitory.toString() === dorm._id.toString());
        const currentCount = currentStudentsInDorm.length;
        
        // 检查是否有男生
        const hasMale = currentStudentsInDorm.some(s => s.gender === '男');
        
        if (currentCount < dorm.capacity && !hasMale) {
          // 分配到这个宿舍
          femaleStudents[i].dormitory = dorm._id;
          await femaleStudents[i].save();
          assigned = true;
        }
        
        attempts++;
      }
    }
    
    // 更新所有宿舍的学生列表
    for (const dorm of freshDorms) {
      const dormStudents = studentDocs.filter(s => s.dormitory && s.dormitory.toString() === dorm._id.toString());
      dorm.students = dormStudents.map(s => s._id);
      await dorm.save();
    }

    // 更新市场部的学生人数
    for (const marketDept of marketDeptDocs) {
      const count = studentDocs.filter(s => s.marketDepartment === marketDept.name).length;
      marketDept.studentCount = count;
      await marketDept.save();
    }

    // 8. 为部分学生添加教师评语
    console.log('添加教师评语...');
    const comments = ['表现优秀，学习认真', '需要加强基础练习', '积极参加课堂活动', '作业完成质量高', '建议多参与实践项目'];
    for (let i = 0; i < 200; i++) {
      const student = studentDocs[Math.floor(Math.random() * studentDocs.length)];
      const teacher = teacherDocs[Math.floor(Math.random() * teacherDocs.length)];
      student.teacherComments.push({
        teacherId: teacher.user,
        teacherName: teacher.name,
        comment: comments[Math.floor(Math.random() * comments.length)],
        commentDate: randomDate(new Date(2024, 0, 1), new Date())
      });
      await student.save();
    }
    console.log('教师评语添加完成');

    // 9. 创建考勤数据（每个学生平均10条考勤记录）
    console.log('创建考勤数据...');
    const attendances = [];
    let serialNumber = 1;
    const startDate = new Date(2024, 0, 1);
    const endDate = new Date();
    
    for (const student of studentDocs) {
      const attendanceCount = Math.floor(Math.random() * 15) + 5; // 每个学生5-20条
      for (let i = 0; i < attendanceCount; i++) {
        const attendanceDate = randomDate(startDate, endDate);
        const status = attendanceStatuses[Math.floor(Math.random() * attendanceStatuses.length)];
        const classDoc = classDocs.find(c => c._id.toString() === student.class.toString());
        const reviewer = userDocs[Math.floor(Math.random() * userDocs.length)];
        
        attendances.push({
          serialNumber: serialNumber++,
          attendanceDate: attendanceDate,
          student: student._id,
          studentName: student.name,
          class: student.class,
          className: classDoc?.className,
          academy: student.academy,
          status: status,
          remark: status !== '正常' ? `考勤异常：${status}` : '',
          reviewer: reviewer._id,
          reviewerName: reviewer.username,
          createdAt: attendanceDate
        });
      }
    }
    
    // 分批插入以避免内存问题
    const batchSize = 1000;
    for (let i = 0; i < attendances.length; i += batchSize) {
      await Attendance.insertMany(attendances.slice(i, i + batchSize));
    }
    console.log(`创建了 ${attendances.length} 条考勤记录`);

    // 10. 创建成绩数据（每个学生每个科目多次考试）
    console.log('创建成绩数据...');
    const grades = [];
    const examTypes = ['周考1', '周考2', '周考3', '月考', '教学月'];
    
    for (const student of studentDocs) {
      // 每个学生每个科目每种考试类型各一条
      for (const subject of subjects.slice(0, 5)) { // 前5个科目
        for (const examType of examTypes) {
          const classDoc = classDocs.find(c => c._id.toString() === student.class.toString());
          const instructor = teacherDocs[10 + Math.floor(Math.random() * 30)]; // 随机讲师
          const score = Math.floor(Math.random() * 40) + 60; // 60-100分
          
          grades.push({
            student: student._id,
            class: student.class,
            subject: subject,
            score: score,
            examType: examType,
            teachingMonth: `${new Date().getFullYear()}年${Math.floor(Math.random() * 12) + 1}月`,
            academy: student.academy,
            instructor: instructor?._id,
            createdAt: randomDate(new Date(2024, 0, 1), new Date()),
            updatedAt: new Date()
          });
        }
      }
    }
    
    // 分批插入
    for (let i = 0; i < grades.length; i += batchSize) {
      await Grade.insertMany(grades.slice(i, i + batchSize));
    }
    console.log(`创建了 ${grades.length} 条成绩记录`);

    // 11. 创建审计日志
    console.log('创建审计日志数据...');
    const auditLogs = [];
    const actions = ['创建', '修改', '删除', '查询', '登录', '登出', '导出', '导入'];
    const modules = ['学生管理', '教师管理', '班级管理', '考勤管理', '成绩管理', '宿舍管理', '市场部管理', '角色权限管理'];
    let logSerialNumber = 1;
    
    for (let i = 0; i < 1000; i++) {
      const user = userDocs[Math.floor(Math.random() * userDocs.length)];
      const action = actions[Math.floor(Math.random() * actions.length)];
      const module = modules[Math.floor(Math.random() * modules.length)];
      const status = Math.random() > 0.1 ? '成功' : '失败'; // 90%成功
      
      auditLogs.push({
        serialNumber: logSerialNumber++,
        timestamp: randomDate(new Date(2024, 0, 1), new Date()),
        user: user._id,
        userId: user._id.toString(),
        username: user.username,
        action: action,
        module: module,
        description: `${action}${module}数据`,
        ipAddress: `192.168.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`,
        status: status
      });
    }
    
    await AuditLog.insertMany(auditLogs);
    console.log(`创建了 ${auditLogs.length} 条审计日志`);

    // 12. 更新角色的用户数量
    console.log('更新角色用户数量...');
    for (const role of roleDocs) {
      const roleCodeMap = {
        '系统管理员': 'admin',
        '院长': 'muster',
        '主任': 'muster',
        '讲师': 'teacher',
        '导员': 'teacher',
        '教务人员': 'user'
      };
      const roleCode = roleCodeMap[role.roleName] || 'user';
      const count = await User.countDocuments({ role: roleCode });
      role.userCount = count;
      role.updatedAt = new Date();
      await role.save();
    }
    console.log('角色用户数量更新完成');

    console.log('\n================== 数据生成完成 ==================');
    console.log(`用户: ${userDocs.length} 个`);
    console.log(`教师: ${teacherDocs.length} 个`);
    console.log(`角色: ${roleDocs.length} 个`);
    console.log(`市场部: ${marketDeptDocs.length} 个`);
    console.log(`班级: ${classDocs.length} 个`);
    console.log(`宿舍: ${dormitoryDocs.length} 个`);
    console.log(`学生: ${studentDocs.length} 个`);
    console.log(`考勤记录: ${attendances.length} 条`);
    console.log(`成绩记录: ${grades.length} 条`);
    console.log(`审计日志: ${auditLogs.length} 条`);
    console.log('================================================\n');

    mongoose.connection.close();
    process.exit(0);
  } catch (error) {
    console.error('数据库初始化失败:', error);
    mongoose.connection.close();
    process.exit(1);
  }
}

// 运行数据初始化
seedDatabase();

